#include"func.h"

int analyze_param(char* input)
{
	if (strlen(input) == 1 && input[0] == '.')
	{
		return LS_NONE;
	}
	else if (strlen(input) == 2)          // 当输入为一个单词时，即-l、-a等
	{
		if (input[1] == 'l')
		{
			return LS_L;
		}
		if (input[1] == 'a')
		{
			return LS_A;
		}
	}
	else if (strlen(input) == 3)
	{
		if ((input[1] == 'l' && input[2] == 'a') || 
			(input[1] == 'a' && input[2] == 'l'))
		{
			return LS_LA;
		}
	}
	return -1;
}

int createDoLsThread(char** message)
{
	pthread_t tid2;
    void *retval;
    int ret_thrd = pthread_create(&tid2, NULL, (void *)&doLs, (void *) message);
    if (ret_thrd != 0) {
        printf("thread doLs create fail\n");
        return -1;
    }
    int tmp = pthread_join(tid2, &retval);
    if (tmp != 0) 
    {
        printf("cannot join with thread doLs\n");
        return -1;
    }
}

int createDoExcelThread(char** message)
{
	pthread_t tid1;
    void *retval;
    int ret_thrd = pthread_create(&tid1, NULL, (void *)&doExecel, (void *) message);
    if (ret_thrd != 0) {
        printf("thread doExcel create fail\n");
        return -1;
    }
    int tmp = pthread_join(tid1, &retval);
    if (tmp != 0) 
    {
        printf("cannot join with thread doExcel\n");
        return -1;
    }
}

int doExecel(void *ptr)
{
	char** message = (char**) ptr;
	mycp(message);
}

char** doLs(void *ptr)
{
	char** message = (char**) ptr;
	char* dirname = message[0];
	int mode = atoi(message[1]);
	char** fileList = (char **)malloc(MAX_FILE_LIST * sizeof(char));
	DIR* dir_ptr;
	struct dirent* direntp;

	char** msg = (char**)malloc(2 * sizeof(char*));

	if ((dir_ptr = opendir(dirname)) == NULL)          // 判断文件夹是否存在
	{
		err_exit("opendir");
	}
	else
	{
		while((direntp = readdir(dir_ptr)) != NULL)
		{
			char* complete_d_name = (char *)malloc(200);
			strcpy(complete_d_name, dirname);
			strcat(complete_d_name, "/");
			strcat(complete_d_name, direntp -> d_name);

			struct stat info;

			if (stat(complete_d_name, &info) == -1)           // 读取文件属性
			{
				err_exit("stat");
			}
            else
            {
            	if (S_IFREG & info.st_mode)                     // 如果当前文件是文件类型
            	{
					char* tmp = (char *)malloc(200);
            		strcpy(tmp, dirname);
            		strcat(tmp, "/");
            		strcat(tmp, direntp -> d_name);
            		free(complete_d_name);
            		complete_d_name = NULL;
					msg[0] = tmp;
					msg[1] = TARGET_FILE_PATH;
					int rel = createDoExcelThread(msg);
					if (rel == -1) err_exit("createDoExcelThread");
            	}
            }
		}
		if (closedir(dir_ptr) == -1)
		{
			err_exit("closedir");
		}
	}
	pthread_exit(NULL);
	return fileList;
}
